/*
 * Copyright 2008 Federal Emergency Management Agency
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0 
 *    
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 *  
 */
package gov.fema.hazus.bdc.client.ui;

import gov.fema.hazus.bdc.client.Constants;
import gov.fema.hazus.bdc.client.UIController;
import gov.fema.hazus.bdc.client.common.BuildingQuery;
import gov.fema.hazus.bdc.client.common.BuildingResults;
import gov.fema.hazus.bdc.client.common.entities.AbstractClickListener;
import gov.fema.hazus.bdc.client.common.handlers.LoggingAsyncHandler;
import gov.fema.hazus.bdc.client.common.ui.Message;
import gov.fema.hazus.bdc.client.common.util.SimpleDateFormat;
import gov.fema.hazus.bdc.client.controller.Controller;
import gov.fema.hazus.bdc.client.login.Login;
import gov.fema.hazus.bdc.client.search.Search;
import gov.fema.hazus.bdc.client.services.BuildingServiceProxy;
import gov.fema.hazus.bdc.client.settings.Settings;
import gov.fema.hazus.bdc.shared.entity.Address;
import gov.fema.hazus.bdc.shared.entity.Building;
import gov.fema.hazus.bdc.shared.entity.Capacity;
import gov.fema.hazus.bdc.shared.entity.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.tools.ant.types.selectors.modifiedselector.HashvalueAlgorithm;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowResizeListener;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TableListener;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class BuildingList extends Composite implements ResizeHandler {

    class BuildingDeleteUpdater extends LoggingAsyncHandler
    {

        public void handleFailure(Throwable caught) {
            GWT.log("Send message to UI:" + caught, null);
            Message.get().setText(caught.getMessage());
        }

        public void handleSuccess(Object result) {
            // getBuildings();
            resetAndGetBuildings();
        }
        
    }
    
    public class BuildingClickListener extends AbstractClickListener
    {

        public void handleClick(Widget sender) {
            
            // the listener is a CellHTML
            CellHTML cell = (CellHTML) sender;
            
            // track the visited buildings
            addVisitedBuilding(cell.buildingId);
            
            // switch UI to buildingDetailUI
            GWT.log("BuildingClickListener, cell id=" + cell.buildingId, null);
            
            // fetch the building based on id
            ////InCAST.get().getBuilding(cell.buildingId);
            Building building = new Building();
            building.setId(cell.buildingId);
            BuildingEditor.get().getBuilding(building);
            
        }
        
    }
    
    private class DeleteButtonClickListener extends AbstractClickListener
    {
        public void handleClick(Widget sender) {
            deleteCheckedBuildings();
        }
    }
    
    private class BuildingTableListener implements TableListener
    {

        public void onCellClicked(SourcesTableEvents sender, int row, int cell) {
            GWT.log("row="+row, null);
            BuildingList.get().getBuilding(row);
        }
        
    }

    private int nextResult = 0;
    private int maxResults = 20;
    private boolean isSearch = false;
    
    private class PreviousSearchClickListener extends AbstractClickListener
    {
        @Override
        public void handleClick(Widget sender) {
            nextResult = (nextResult - 20);
            BuildingList.get().executeSearch( Search.get().getQuery() );
        }
    }
    
    private class NextSearchClickListener extends AbstractClickListener
    {
        public void handleClick(Widget sender) {
            nextResult = (nextResult + 20);
            BuildingList.get().executeSearch( Search.get().getQuery() );
        }
    }
    
    private class PreviousButtonClickListener extends AbstractClickListener
    {
        public void handleClick(Widget sender) {
            nextResult = (nextResult - 20);
            GWT.log("PreviousButtonClickListener isSearch="+isSearch, null);
            if( isSearch )
            {
                BuildingList.get().executeSearch( Search.get().getQuery() );
            }
            else
            {
                getBuildings();
            }
        }
        
    }
    
    private class NextButtonClickListener extends AbstractClickListener
    {

        public void handleClick(Widget sender) {
            nextResult = (nextResult + 20);
            GWT.log("NextButtonClickListener isSearch="+isSearch, null);
            if( isSearch )
            {
               BuildingList.get().executeSearch( Search.get().getQuery() );
            }
            else
            {
                getBuildings();
            }
        }
        
    }    

    public PaginationControls paginationControls;
    
    private class BuildingListHandler extends LoggingAsyncHandler
    {

        @Override
        public void handleFailure(Throwable caught) {
           GWT.log("handle building list failure" + caught, null);
        }

        @Override
        public void handleSuccess(Object result) {
            
            
            GWT.log("handle building list success", null);
            
            Controller.get().mainShowBuildingList();
            
            UIController.get().restoreTitle();
            Message.get().hide();
            
            BuildingResults buildingResults = (BuildingResults) result;
            BuildingQuery query = buildingResults.getBuildingQuery();
            
            ArrayList<Building> buildings = buildingResults.getBuildings();
            
            setBuildings(buildings);
            
            GWT.log("buildings=" + buildings, null);
            
            int first = query.getNext();
            first++;
            paginationControls.setFirst(Integer.toString(first));
            
            int last = first + query.getMax() - 1;
            paginationControls.setLast(Integer.toString(last));
            
            int total = query.getTotal();
            paginationControls.setTotal(Integer.toString(total));
            
            // don't go off the end
            if( last >= total)
            {
                last = total;
                paginationControls.setLast(Integer.toString(last));
                paginationControls.hideNext();
            }
            else
            {
                paginationControls.showNext();
            }
            
            // don't go off the beginning
            if( first <= 1)
            {
                paginationControls.hidePrevious();
            }
            else
            {
                paginationControls.showPrevious();
            }           
            
            GWT.log("We have "+first+" to "+last+" of "+total+" buildings", null);

            // toggle the color of the UI
            toggleUISearchColor(isSearch);
            
            
            // do the right thing with the highlight on the left nav
            if( isSearch )
            {
                LeftNavigation.get().highlightLeftNav("NONE");
            }
            else
            {
                LeftNavigation.get().highlightLeftNav(constants.leftnavListBuildings());
            }
            
            // redraw the table
            redrawTable(buildings);

            // show the building list
            Controller.get().mainShowBuildingList();
            
        }
        
    }
    
    // widgets
    FlexTable table = new FlexTable();
    
    
    // handlers
    private BuildingListHandler buildingListHandler = new BuildingListHandler();
    private BuildingClickListener buildingClickListener = new BuildingClickListener();

    private ArrayList<Building> buildings;
    private ArrayList<CheckBox> checkBoxes = new ArrayList<CheckBox>();
    private HashMap<Long, Long> visitedBuildings = new HashMap<Long, Long>();
    private NextButtonClickListener nextButtonClickListener;
    private PreviousButtonClickListener previousButtonClickListener;
    private Constants constants;
    private SimpleDateFormat formatter;
    private DockPanel docker;
    private HorizontalPanel northButtonBar;
    private HTML serverMessagePlaceholder;
    private HorizontalPanel southButtonBar;
    private LockImageBundle lockIcon;
	private TabPanel tabPanel;
	private PreviousSearchClickListener previousSearchClickListener;
    
    /**
     * Set up instance for Login
     */
    private static BuildingList singleton;
    public static BuildingList get()
    {
        if( singleton == null )
        {
            singleton = new BuildingList();
        }
        return singleton;
    }
    
    public void getBuilding(int row) {
        if( buildings != null )
        {
            if( buildings.size() >= row )
            {
                Building clickedBuilding = buildings.get(row);
                BuildingEditor.get().getBuilding(clickedBuilding);
            }
        }
    }

    public void setBuildings(ArrayList<Building> buildings) {
        this.buildings = buildings;
    }

    public BuildingList()
    {
        
        singleton = this;
        
        // constants
        constants = (Constants)GWT.create(Constants.class);
        
        // create the lock image bundle
        lockIcon = (LockImageBundle)GWT.create(LockImageBundle.class);
        
        
        // tracker
        visitedBuildings = new HashMap<Long, Long>();
        checkBoxes = new ArrayList<CheckBox>();
        
        // components
        docker  = new DockPanel();
        tabPanel = new TabPanel();
        table = new FlexTable();
        
        
        // pagination listeners
        nextButtonClickListener = new NextButtonClickListener();
        previousButtonClickListener = new PreviousButtonClickListener();
        new NextSearchClickListener();
        previousSearchClickListener = new PreviousSearchClickListener();
        
        // setup pagination with default button listeners
        paginationControls = new PaginationControls(nextButtonClickListener, previousButtonClickListener);
        
        // add the table to the docker
        docker.add(table, DockPanel.CENTER);
        docker.setCellVerticalAlignment(table, HasVerticalAlignment.ALIGN_TOP);
        docker.setCellHeight(table, "100%");
        
        // north button bar
        northButtonBar = new HorizontalPanel();
        northButtonBar.setStyleName("north-button-bar");
        
        // delete buttons
        Button deleteButtonTop = new Button();
        deleteButtonTop.setStyleName("incast-command-button");
        deleteButtonTop.setText(constants.deleteButton());
        deleteButtonTop.addClickListener(new DeleteButtonClickListener());
        northButtonBar.add(deleteButtonTop);
        
        // error placeholder
        serverMessagePlaceholder = new HTML();
        
        northButtonBar.add(serverMessagePlaceholder);
        northButtonBar.add(paginationControls);
        northButtonBar.setCellHorizontalAlignment(paginationControls, HasHorizontalAlignment.ALIGN_RIGHT);
        
        // south button bar
        southButtonBar = new HorizontalPanel();
        southButtonBar.setStyleName("south-button-bar");     

        Button deleteButtonBottom = new Button();
        deleteButtonBottom.setStyleName("incast-command-button");
        deleteButtonBottom.setText(constants.deleteButton());
        deleteButtonBottom.addClickListener(new DeleteButtonClickListener());
        southButtonBar.add(deleteButtonBottom);
        
        FlexTable southTable = new FlexTable();
        southTable.setWidth("100%");
        southTable.setWidget(0, 0, new HTML(""));
        southButtonBar.add(southTable);
        southButtonBar.setCellWidth(southTable, "100%");
        southButtonBar.setCellHorizontalAlignment(southTable, HasHorizontalAlignment.ALIGN_RIGHT);
        
        docker.add(northButtonBar, DockPanel.NORTH);
        docker.add(southButtonBar, DockPanel.SOUTH);
        docker.setCellWidth(southButtonBar, "100%");
        docker.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);

        docker.setStyleName("docker-building-detail");
        
        initWidget(docker);
                
    }
    
    public void getBuildings()
    {
        //BuildingQuery buildingQuery = new BuildingQuery();
        // not actually using the query for the stub, so no worries about filling it
        //SearchServiceProxy.get().find(buildingQuery, buildingListHandler);
        
        // InCAST keeps track of the buildings
        //if( InCAST.get().getBuildings() == null )
        //{
            
            BuildingQuery buildingQuery = new BuildingQuery();
            buildingQuery.setMax(maxResults);
            buildingQuery.setAscending(true);
            buildingQuery.setNext(nextResult);
            BuildingServiceProxy.get().find(buildingQuery, buildingListHandler);
        /*
        }
        else
        {
            GWT.log("no buildings in InCAST, so fetch them", null);
        }
        */
        
    }
    
    private void redrawTable(ArrayList<Building> buildings)
    {
        table.setVisible(true);
        
        
        
        // from the end, remove each row
        for (int i=table.getRowCount()-1; i>=0;i--){
            table.removeRow(i);
        }
        // and clear the widgets
        table.clear();
        
        table.setStyleName("building-list-table");
        checkBoxes.clear();
        
        int row = 0;
        for (Iterator<Building> iterator = buildings.iterator(); iterator.hasNext();) {
            
            Building building = (Building) iterator.next();

            String oneLiner = "";
            //oneLiner += "<b>"+building.getName()+"</b>";
            oneLiner += " (# "+building.getNumber()+") ";
            
            Address addr = building.getAddress();
            String address = "";
            if( addr != null)
            {
	            if( addr.getStreet1() != null )
	            {
	                address += addr.getStreet1();
	            }
	            if( addr.getStreet2() != null )
	            {
	                address += " " + addr.getStreet2();
	            }
	            if( addr.getCity() != null )
	            {
	                address += " " + addr.getCity();
	            }
	            if( addr.getState() != null )
	            {
	                address += " " + addr.getState();
	            }
	            if( addr.getPostalCode() != null )
	            {
	                address += " " + addr.getPostalCode();
	            }
            }
            oneLiner += " "+address;
            
            if( building.getConstructionYear() != null )
            {
                oneLiner += ", "+building.getConstructionYear();
            }
            
            if( building.getCapacity() != null )
            {
                Capacity c = building.getCapacity();
                oneLiner += ", "+constants.dayOcc()+" ("+c.getDaytimeOccupants()+"), ";
                oneLiner += " "+constants.nightOcc()+" ("+c.getNighttimeOccupants()+") ";
            }
            
            String formattedDate = "";
            if( building.getLastMod() != null )
            {
                Date lastMod = building.getLastMod();
                Date today = new Date();
                
                if( lastMod.getYear() == today.getYear() 
                        && lastMod.getMonth() == today.getMonth()
                        && lastMod.getDate() == today.getDate() )
                {
                    formatter = new SimpleDateFormat("hh:mm a");
                }
                else
                {
                    // TODO: localize the date format string
                    formatter = new SimpleDateFormat("MM/dd/yyyy");
                }
                formattedDate = formatter.format(lastMod);
                
            }
            
            // build up the cells
            String buildingId = null;
            if( building.getId() != null )
            {
                buildingId = building.getId().toString();
            }
            CheckBox buildingCheckBox = new CheckBox();
            buildingCheckBox.setName(buildingId);
            checkBoxes.add(buildingCheckBox);
            
            CellHTML buildingNumber = new CellHTML(building.getId(), building.getNumber());
            CellHTML buildingName = new CellHTML(building.getId(), building.getName());
            CellHTML buildingAbbreviation = new CellHTML(building.getId(), building.getAbbreviation());
            CellHTML buildingLastMod = new CellHTML(building.getId(), formattedDate);
            buildingLastMod.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
            
            /*
             * add lat, long, construction year, day/night occupants
             * to address string
             */
            /*
            Location location = building.getLocation();
            String loc = "";
            if( location != null )
            {
                loc += " ("+location.getLatitude()+","+location.getLongitude()+") ";
                address += loc;
            }
            */
            
            CellHTML buildingAddress = new CellHTML(building.getId(), address);
            CellHTML buildingLongDescription = new CellHTML(building.getId(), oneLiner);
            
            // if we have visited this before, show that in the css
            //flexTable.getRowFormatter().setStyleName(row, "building-list-item");
            
            if( visitedBuildings.containsKey(building.getId()))
            {
                
                table.getRowFormatter().setStyleName(row, "building-list-item-visited");
                buildingName.setStyleName("bldg-name-visited");
                buildingLongDescription.setStyleName("bldg-description-visited");
                buildingLastMod.setStyleName("bldg-description-visited");
                /*
                buildingCheckBox.setStyleName("bldg-name-visited");
                buildingName.setStyleName("bldg-name-visited");
                buildingNumber.setStyleName("bldg-name-visited");
                
                buildingAddress.setStyleName("bldg-name-address-visited");
                buildingLastMod.setStyleName("bldg-name-address-visited");
                buildingLongDescription.setStyleName("bldg-name-address-visited");
                */
            }
            else
            {
                
                table.getRowFormatter().setStyleName(row, "building-list-item");
                buildingName.setStyleName("bldg-name");
                buildingLongDescription.setStyleName("bldg-description");
                buildingLastMod.setStyleName("bldg-description");
                /*
                buildingCheckBox.setStyleName("bldg-name");
                buildingName.setStyleName("bldg-name");
                buildingNumber.setStyleName("bldg-name");
                
                buildingAddress.setStyleName("bldg-name-address");
                buildingLastMod.setStyleName("bldg-name-address");
                buildingLongDescription.setStyleName("bldg-name-address");
                */
            }
            
            table.getRowFormatter().setVerticalAlign(row, HasVerticalAlignment.ALIGN_MIDDLE);
            //buildingAddress.setWidth("100%");

            table.setWidget(row, 0, buildingCheckBox);
            
            /*
             * Insert a lock image (3 cases)
             * 1. There is no user attached to this building. No lock
             * 2. There is a user attached to this building. The user is us: myLock
             * 3. There is a user attached to this building. The user is not us: otherLock 
             */
            Image lockImage = null;
            String currentUser = building.getUserName();
            
            GWT.log("currentUser=" + currentUser, null);
            if( currentUser.equalsIgnoreCase("") )
            {
                lockImage = lockIcon.noLock().createImage();
            }
            else
            {
                // if the username is the same as the login username, use myLock
            	User loginUser = Login.get().getLoginUser();
            	if( loginUser != null )
                {
                    if( loginUser.getUsername().equalsIgnoreCase( currentUser ))
                    {
                        // use myLock
                        lockImage = lockIcon.myLock().createImage();
                    }
                    else
                    {
                        // use otherLock
                        lockImage = lockIcon.otherLock().createImage();

                    }
                }
                
            }
            lockImage.setTitle(currentUser);
            //lockImage.setHeight("12px");
            //lockImage.setWidth("15px");
            
           
            table.getRowFormatter().setVerticalAlign(row, HasVerticalAlignment.ALIGN_MIDDLE);
            
            table.setWidget(row, 1, lockImage);
            table.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_TOP);
            
            
            table.setWidget(row, 2, buildingName);
            table.setWidget(row, 3, buildingLongDescription);
            table.setWidget(row, 4, buildingLastMod);

            
            paginationControls.setVisible(true);
            
            // increment the row
            row++;

        }
        
        table.setVisible(true);
        
    }
    
    
    
    public class CellHTML extends HTML
    {
        public Long buildingId;
        
        public CellHTML(Long buildingId, String text)
        {
            this.buildingId = buildingId;
            this.setText(text);
            this.addClickListener(buildingClickListener);
        }
    }    
    
    private void deleteCheckedBuildingsOK()
    {
        ArrayList<Building> buildings = new ArrayList<Building>();
        Building building;
        String idStr;
    
        // find out the current user
        User currentUser = Login.get().getLoginUser();

		/*
		 * run through this.buildings (should be page size only)
		 * and make a map of <ID, currentUser> to test against
		 * when we go to delete them
		 */
		HashMap<Long, String> buildingLockUsers = new HashMap<Long, String>();
		for (Iterator iterator = this.buildings.iterator(); iterator.hasNext();) {
			Building b = (Building) iterator.next();
			buildingLockUsers.put(b.getId(), b.getUserName());
		}
		
        // walk through the checkboxes array
        for (Iterator<CheckBox> iter = checkBoxes.iterator(); iter.hasNext();) {
            CheckBox cb = (CheckBox) iter.next();
            if(cb.isChecked())
            {
                // the checkbox name is the building id, convert to Long
                idStr = cb.getName();
                Long id = Long.parseLong(idStr);
                
                // create a building to delete
                building = new Building();
                
                // set the id
                building.setId(id);
                
                /*
                 * Don't include buildings whose user names don't match
                 * the current user name -- prevents a user from deleting
                 * another users locked building
                 */
                String buildingUserName = buildingLockUsers.get(id); 
                GWT.log("id("+id+"), username("+buildingUserName+")", null);
                if( buildingUserName != null 
                		&& buildingUserName.equalsIgnoreCase(currentUser.getUsername()))
                {
                	// we have the same username, so add it to the buildings to be deleted
                    buildings.add(building);
                } else {
                	GWT.log("usernames don't match, so don't add this building for deletion", null);
                }
                
                
                
            }
        }
        
        // start pass the list of buildings to be deleted to the api
        // BuildingDeleteUpdater will refetch the buildings
        GWT.log("buildings to delete=" + buildings, null);
        BuildingServiceProxy.get().deleteBuildings(buildings, new BuildingDeleteUpdater());
    }
    
    private void uncheckBuildings()
    {
        for (Iterator<CheckBox> iter = checkBoxes.iterator(); iter.hasNext();) {
            CheckBox cb = (CheckBox) iter.next();
            if( cb.isChecked() )
            {
                cb.setChecked(false);
            }
        }
    }
    
    public void deleteCheckedBuildings() {
        
        final DialogBox box = new DialogBox();
        
        // vpanel to hold everything
        VerticalPanel vp = new VerticalPanel();
        vp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        
        // add the message
        HTML deleteMessagae = new HTML(constants.deleteConfirm());
        deleteMessagae.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        vp.add(deleteMessagae);
        
        box.setText(constants.warning());
        box.setWidth("200");
        
        // add buttons
        Button dontDelete = new Button(constants.cancelButton());
        dontDelete.addClickListener(new ClickListener(){

            public void onClick(Widget sender) {
                box.hide();
                uncheckBuildings();
            }
            
        });
        
        Button okDelete = new Button(constants.ok());
        okDelete.addClickListener(new ClickListener(){

            public void onClick(Widget sender) {
                box.hide();
                deleteCheckedBuildingsOK();
            }
            
        });
        
        HorizontalPanel buttons = new HorizontalPanel();
        buttons.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        
        buttons.add(okDelete);
        buttons.add(dontDelete);
        
        vp.add(buttons);
        
        
        box.add(vp);
        
        box.center();
        box.show();
        
        /*
        // confirm deletion
        if( Window.confirm( constants.deleteConfirm() ))
        {
            
            ArrayList buildings = new ArrayList();
            Building building;
            Long id;
        
            // walk through the checkboxes array
            for (Iterator iter = checkBoxes.iterator(); iter.hasNext();) {
                CheckBox cb = (CheckBox) iter.next();
                if(cb.isChecked())
                {
                    // the checkbox name is the building id, convert to Long
                    id = new Long(cb.getName());
                    
                    // create a building to delete
                    building = new Building();
                    
                    // set the id
                    building.setId(id);
                    
                    // add it to the buildings to be deleted
                    buildings.add(building);
                    
                }
            }
            
            // start pass the list of buildings to be deleted to the api
            // BuildingDeleteUpdater will refetch the buildings
            GWT.log("buildings to delete=" + buildings, null);
            SearchServiceProxy.get().deleteBuildings(buildings, new BuildingDeleteUpdater());
        }
        */
    }
 
    public static void actionWrapperResetAndExecuteSearch()
    {
    	BuildingList.get().resetAndExecuteSearch(Search.get().getQuery());
    }
    
    public void resetAndExecuteSearch(String query) {
        nextResult = 0;
        maxResults = 20;
        executeSearch(query);
    }   
    
    public void executeSearch(String searchTerm) {
        isSearch = true;
        GWT.log("Executing search with query=" + searchTerm, null);
        GWT.log("Executing search with nextResult=" + nextResult, null);
        GWT.log("Executing search with maxResults=" + maxResults, null);
        BuildingQuery query = new BuildingQuery();
        query.setNext(nextResult);
        query.setMax(maxResults);
        query.setSearchTerm(searchTerm);
        BuildingServiceProxy.get().search(query, buildingListHandler);
    }
    
    public void toggleUISearchColor(boolean search)
    {

        if( search )
        {
            docker.setStyleName("docker-building-detail-search");
            northButtonBar.setStyleName("north-button-bar-search");
            southButtonBar.setStyleName("south-button-bar-search");
            
            UIController.get().setSearchBorder(true);
            //LeftNavigation.get().highlightLeftNav("NONE");
            
        }
        else
        {
            docker.setStyleName("docker-building-detail");
            northButtonBar.setStyleName("north-button-bar");
            southButtonBar.setStyleName("south-button-bar");
            
            UIController.get().setSearchBorder(false);
            //LeftNavigation.get().highlightLeftNav(constants.leftnavListBuildings());            
        }
        
        
    }

    public void setSearchFlag(boolean b) {
        isSearch = b;
    }

    public void resetAndGetBuildings() {
    	GWT.log("reset and get buildings, change search flag to false", null);
    	nextResult = 0;
        maxResults = 20;
        setSearchFlag(false);
        getBuildings();
    }

    public void addVisitedBuilding(Long buildingId) {
        visitedBuildings.put(buildingId, buildingId);
    }

    /*
     * ActionWrappers are called by the Controller, which
     * must call static methods and cannot call instance
     * methods directly. Thus, we wrap an singleton method
     * within a static method.
     */

    private static void actionWrapperGetBuildings()
    {
    	BuildingList.get().setSearchFlag(false);
    	BuildingList.get().resetAndGetBuildings();
    }

	public void onResize(ResizeEvent event) {
		GWT.log("BuildingList resize", null);
	}
}
